package com.xgp.labblog.controller;

import com.xgp.labblog.model.Writes;
import com.xgp.labblog.service.WriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Null;
import java.util.List;
import java.util.Optional;


@Controller
public class IndexController {

    @Autowired
    WriteService writeService;

    @Value("${labblog.client.notice}")
    String notice;

    @GetMapping("/")
    public String index(Model model, @RequestParam(value = "title",required=false,defaultValue = "") String title) {
        try {
            //        System.out.println(title);
            List<Writes> Writelist = null;
            //1，定义全局变量，查询前五条数据
            if(title.isEmpty()) {
                Writelist = writeService.FindWriteByTime(5);
            }else {
                Writelist = writeService.FindWriteByTimeAndTitle(5,title);
            }
            for (Writes write : Writelist) {
                //2，调整正文内容
                write.setText(write.getText().substring(0,write.getText().length() > 100 ? 100 : write.getText().length()) + "......");
//            System.out.println(write);
            }
            //3,将数据放回给页面
            model.addAttribute("IndexWriteList",Writelist);
            model.addAttribute("notice",notice);
            //4，跳转页面
            return "html/index";

        }catch (Exception e) {
            return "error/4xx";
        }
    }


    @GetMapping("/supper-write/{id}")
    @ResponseBody
    public void supperWrite(@PathVariable(name = "id") Integer id) {
        writeService.addSupCount(id);
    }

    @GetMapping("/randWrite")
    public String randWrite(Model model) {

        try {
            //1，定义全局变量，查询前五条数据
            List<Writes> Writelist = writeService.FindWriteRand(5);
            for (Writes write : Writelist) {
                //2，调整正文内容
                write.setText(write.getText().substring(0,write.getText().length() > 100 ? 100 : write.getText().length()) + "......");
//            System.out.println(write);
            }
            //3,将数据放回给页面
            model.addAttribute("IndexWriteList",Writelist);
            model.addAttribute("notice",notice);
            //4，跳转页面
            return "html/index";
        }catch (Exception e) {
            return "error/4xx";
        }

    }
}
